package cn.sylinx.common.lang;

/**
 * 十六进制字符串和普通字符串之间的转换
 *
 */
public class HexUtil {
    /**
     * 将字符串转换为十六进制字符串
     *
     * @param str 普通字符串
     *
     * @return 转换后的十六进制字符串
     */
    public static String str2HexString(String str) {
        String ret = "";
        byte[] b   = str.getBytes();

        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);

            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            ret += hex.toUpperCase();
        }

        return ret;
    }

    /**
     * 将十六进制字符串转换为普通字符串
     *
     * @param hexStr 十六进制字符串
     *
     * @return 转换后的普通字符串
     */
    public static String hexString2Str(String hexStr) {
        String ret = "";

        byte   before = Byte.MAX_VALUE;

        for (int i = 0; i < (hexStr.length() / 2); i++) {
            String tmpStr = hexStr.substring(i * 2, (i + 1) * 2);

            byte[] tmpByte = tmpStr.getBytes();

            byte[] resByte = new byte[1];

            resByte[0] = uniteBytes(tmpByte[0], tmpByte[1]);

            if (resByte[0] < 0) {
                if (before < 0) {
                    byte[] tmp = new byte[2];

                    tmp[0] = before;
                    tmp[1] = resByte[0];
                    ret += new String(tmp);
                    before = '0';
                    continue;
                }
            } else {
                ret += new String(resByte);
            }

            before = resByte[0];
        }

        return ret;
    }

    private static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();

        _b0 = (byte) (_b0 << 4);

        byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
        byte ret = (byte) (_b0 ^ _b1);

        return ret;
    }
}